package org.jetbrains.kotlin.generators.arguments

import org.jetbrains.kotlin.arguments.dsl.types.KotlinVersion as ArgsKotlinVersion
import org.jetbrains.kotlin.utils.Printer
import java.io.File

fun main() {
    generateUnsupportedGradleLanguageVersionsMetadata(::getPrinterToFile)
}

private const val GRADLE_PLUGIN_SRC_DIR = "libraries/tools/kotlin-gradle-plugin/src/common/kotlin"

fun generateUnsupportedGradleLanguageVersionsMetadata(withPrinterToFile: (targetFile: File, Printer.() -> Unit) -> Unit) {
    val targetFile = File(
        "$GRADLE_PLUGIN_SRC_DIR/org/jetbrains/kotlin/gradle/internal/UnsupportedKotlinLanguageVersionsMetadata.kt"
    )

    withPrinterToFile(targetFile) {
        println("// DO NOT EDIT MANUALLY! Generated by ${object {}.javaClass.enclosingClass.name}")
        println("// To regenerate run 'generateUnsupportedGradleLanguageVersionsMetadata' task")
        println("@file:Suppress(\"RemoveRedundantQualifierName\", \"Deprecation\", \"Deprecation_Error\", \"DuplicatedCode\")")
        println()
        println("package org.jetbrains.kotlin.gradle.internal")
        println()
        println("import org.jetbrains.kotlin.gradle.dsl.KotlinVersion")
        println("import org.jetbrains.kotlin.tooling.core.KotlinToolingVersion")
        println()
        println("internal object UnsupportedKotlinLanguageVersionsMetadata {")
        withIndent {
            println("internal class UnsupportedKotlinLanguageVersionMetadata(val deprecationVersion: KotlinToolingVersion, val removalVersion: KotlinToolingVersion?)")
            println()
            println("internal val unsupportedPerVersion: Map<KotlinVersion, UnsupportedKotlinLanguageVersionMetadata> = mapOf(")
            withIndent {
                for (version in ArgsKotlinVersion.entries) {
                    val gradleEnumName = "KOTLIN_" + version.versionName.replace('.', '_')
                    val meta = version.releaseVersionsMetadata
                    val deprecationVersion = meta.deprecatedVersion ?: continue
                    val removalVersion = meta.removedVersion
                    val lowestPossibleClassifier = "\"snapshot\""
                    val removalVersionString =
                        removalVersion?.let { "KotlinToolingVersion(${removalVersion.major}, ${removalVersion.minor}, ${removalVersion.patch}, $lowestPossibleClassifier)" }
                    println(
                        "KotlinVersion.$gradleEnumName to UnsupportedKotlinLanguageVersionMetadata(KotlinToolingVersion(${deprecationVersion.major}, ${deprecationVersion.minor}, ${deprecationVersion.patch}, $lowestPossibleClassifier), $removalVersionString),"
                    )
                }
            }
            println(")")
        }
        println("}")
    }
}
